package com.dlx.msm.controller;

import com.dlx.common.result.Result;
import com.dlx.msm.service.MsmService;
import com.dlx.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api("消息服务")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation("手机短信发送接口")
    @GetMapping("/send/{mobile}")
    public Result sendCode(@PathVariable String mobile){
        //从redis获取验证码,如果获取的到,返回ok
        //key 手机号,value 验证码
        String code = redisTemplate.opsForValue().get(mobile);
        if(StringUtils.hasText(code)){
            return Result.ok();
        }

        //如果获取不到,生成验证码,通过整合短信服务进行发送
        code = RandomUtil.getSixBitRandom();
        //调用service方法实现
        boolean isSend = msmService.send(mobile,code);
        //生成验证码放到redis中,设置有效时间
        if(isSend){
            redisTemplate.opsForValue().set(mobile,code,5, TimeUnit.MINUTES);
            return Result.ok();
        }else{
            return Result.fail().message("发送短信失败");
        }
    }

    @ApiOperation("邮件发送接口")
    @GetMapping("/sentEmail/{email}")
    public Result sentEmail(@PathVariable String email){
        String code = redisTemplate.opsForValue().get(email);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        code = RandomUtil.getSixBitRandom();
        boolean isSend = msmService.send(email,"注册验证码",code);
        if(isSend){
            redisTemplate.opsForValue().set(email,code,2,TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("短信发送失败");
        }
    }
}
